<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色表单</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      <!-- 表格区域 -->
      <el-table :data="roleList" border stripe style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand" width="50">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(right1, i1) in scope.row.children" :key="right1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, right1)">{{right1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(right2, i2) in right1.children" :key="right2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, right2)">{{right2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" closable v-for="(right3) in right2.children"
                    :key="right3.id" @close="removeRightById(scope.row, right3)">
                      {{right3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"> 编辑</el-button>
            <!-- 删除按钮 -->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row)">删除</el-button>
            <!-- 分配权限按钮 -->
              <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible"
      width="30%" @close="addDialogClosed">
      <!-- 对话框: 内容主题区 -->
      <el-form ref="addFormRef" :model="newRole" :rules="roleRules"
        label-width="80px" label-position="right">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="newRole.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="newRole.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色的对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="30%" @close="editDialogClosed">
      <!-- 编辑对话框: 内容主题区 -->
      <el-form ref="editFormRef" :model="editRole" :rules="roleRules"
        label-width="80px" label-position="right">
        <el-form-item label="角色ID">
          <el-input v-model="editRole.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="editRole.roleName" prop="roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="40%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree
        ref="treeRef"
        :data="rightTree"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defaultCheckedKeys"
        :props="defaultProps">
      </el-tree>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSetRight">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色表单
      roleList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      newRole: {
        roleName: '',
        roleDesc: ''
      },
      editRole: {},
      // 要分配权限的角色id
      roleId: '',
      // 所有权限列表
      rightTree: [],
      defaultProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值
      defaultCheckedKeys: [],
      // 角色校验规则
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { whitespace: true, message: '角色名称不能为空格', trigger: 'blur' }
        ],
        roleDesc: [
          { whitespace: true, message: '角色描述不能为空格', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 监听对话框关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    setRightDialogClosed() {
      this.defaultCheckedKeys = []
      this.rightTree = []
      this.roleId = ''
    },
    // 获取角色表单
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
    },
    // 提交"添加角色"表单
    submitAddForm() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('roles', this.newRole)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败!')
        } else {
          this.$message.success('添加角色成功!')
          this.addDialogVisible = false
          this.getRoleList()
        }
      })
    },
    // 显示编辑对话框
    async showEditDialog(roleId) {
      const { data: res } = await this.$http.get('roles/' + roleId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRole = res.data
      this.editDialogVisible = true
    },
    // 提交"编辑角色"表单
    submitEditForm() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`roles/${this.editRole.roleId}`, {
          roleName: this.editRole.roleName,
          roleDesc: this.editRole.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('角色修改成功')
        this.editDialogVisible = false
        this.getRoleList()
      })
    },
    // 删除角色
    async deleteRole(role) {
      const result = await this.$messageBox.confirm('此操作将删除角色: ' + role.roleName + ', 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + role.id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRoleList()
    },
    // 根据id删除权限
    async removeRightById(role, right) {
      const result = await this.$messageBox.confirm('此操作将删除角色: ' + role.roleName + '的权限: ' + right.authName + ', 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${right.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      role.children = res.data
    },
    // 显示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightTree = res.data
      this.getDefaultCheckedKeys(role, this.defaultCheckedKeys)
      this.setRightDialogVisible = true
    },
    // 递归获取当前角色的所有权限id
    getDefaultCheckedKeys(node, defaultCheckedKeys) {
      if (!node.children) {
        return defaultCheckedKeys.push(node.id)
      }
      node.children.forEach(item => {
        this.getDefaultCheckedKeys(item, defaultCheckedKeys)
      })
    },
    // 点击为角色分配权限
    async submitSetRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const ridStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: ridStr })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.setRightDialogVisible = false
      this.getRoleList()
    }
  }
}
</script>

<style lang="less" scoped></style>
